package com.xci.sys.controller;

import com.google.common.collect.Lists;
import com.xci.core.annotation.Authorize;
import com.xci.core.base.RestMessage;
import com.xci.core.base.WebController;
import com.xci.core.exceptions.EntityNotFoundException;
import com.xci.core.helper.ConvertHelper;
import com.xci.core.helper.ExcelHelper;
import com.xci.core.helper.Helper;
import com.xci.core.helper.TreeHelper;
import com.xci.core.internal.Const;
import com.xci.core.web.TreeNodeIndex;
import com.xci.sys.entity.SysDept;
import com.xci.sys.filter.DeptFilter;
import com.xci.sys.filter.UserFilter;
import com.xci.sys.service.DeptService;
import com.xci.sys.service.RoleService;
import com.xci.sys.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * 系统组织机构控制器
 * @author 吕艳阳
 */
@Authorize
@Slf4j
@Controller
@RequestMapping("/sys/dept")
public class DeptController extends WebController {
    @Resource
    private UserService userService;//用户服务
    @Resource
    private DeptService deptService;//部门服务
    @Resource
    private RoleService roleService;//角色服务
    // region 页面视图

    /**
     * 组织机构首页
     */
    @GetMapping
    @Authorize(code = "SystemDepartment")
    public String index() {
        return "sys/dept/index";
    }

    /**
     * 组织机构新建页面
     */
    @GetMapping("/create")
    @Authorize(code = "SystemDepartment.Create")
    public String create(String parentId, ModelMap map) {
        createMark(map);
        SysDept entity = new SysDept();
        entity.setId(Helper.nextIdStr());
        entity.setParentId(parentId);
        entity.setStatus(true);
        map.put("entity", entity);
        map.put("parentName", getParentName(parentId));
        var userFilter = new UserFilter();
        userFilter.setStatus(true);
        userFilter.setAll(true);
        map.put("managerUserList", userService.selectSimpleList(userFilter));
        return "sys/dept/edit";
    }

    /**
     * 组织机构编辑页面
     */
    @GetMapping("/edit")
    @Authorize(code = "SystemDepartment.Edit")
    public String edit(String id, ModelMap map) {
        SysDept entity = deptService.selectById(id);
        if (entity == null) throw new EntityNotFoundException(id);
        
        map.put("entity", entity);
        map.put("parentName", getParentName(entity.getParentId()));
        var userFilter = new UserFilter();
        userFilter.setStatus(true);
        userFilter.setAll(true);
        map.put("managerUserList", userService.selectSimpleList(userFilter));
        return "sys/dept/edit";
    }

    private String getParentName(String id) {
        String parentName = Const.EMPTY;
        if (Helper.isNotBlank(id) && !id.equals(Const.ROOT_NODE_ID)) {
            var parentModel = deptService.selectById(id);
            if (parentModel!= null){
                parentName = parentModel.getName();
            }
        }
        if (Helper.isBlank(parentName)){
            parentName = "顶层组织机构";
        }
        return parentName;
    }

    /**
     * 组织机构详细页面
     *
     * @param id 组织机构主键
     */
    @GetMapping("/details")
    public String details(String id, ModelMap map) {
        SysDept entity = deptService.selectById(id);
        if (entity == null) throw new EntityNotFoundException(id);
        
        map.put("entity", entity);
        map.put("parentName", getParentName(entity.getParentId()));
        map.put("users",userService.selectListByDeptId(id));
        return "sys/dept/details";
    }

    //endregion

    //region 数据处理

//    /**
//     * 组织机构Tree
//     */
//    @ResponseBody
//    @GetMapping("/tree")
//    public Object tree(@RequestParam Map<String, String> params) {
//        params.put("status", "1");
//        List<SysDept> list = deptService.query(params);
//        List<TreeNode> models = deptService.convertToNodeList(list);
//        return RestMessage.tree(models);
//    }

    /**
     * 用户拥有的部门 tree 节点
     */
    @ResponseBody
    @GetMapping("/user-own-departments")
    public RestMessage userOwnDepartments() {
        var filter = new DeptFilter();
        filter.setStatus(true);
        List<SysDept> departments = deptService.selectList(filter);
        return RestMessage.tree(deptService.convertToNodeList(departments));
    }

    /**
     * 组织机构表格数据
     */
    @ResponseBody
    @GetMapping("/grid")
    @Authorize(code = "SystemDepartment.Search")
    public Object grid(DeptFilter filter) {
        List<SysDept> list = deptService.selectList(filter);
        return RestMessage.grid(list);
    }

    /**
     * 保存组织机构
     */
    @ResponseBody
    @PostMapping("/createSave")
    @Authorize(code = "SystemDepartment.Create")
    public RestMessage createSave(@ModelAttribute SysDept entity) {
        return deptService.insert(entity);
    }

    /**
     * 保存组织机构
     */
    @ResponseBody
    @PostMapping("/updateSave")
    @Authorize(code = "SystemDepartment.Edit")
    public RestMessage editSave(@ModelAttribute SysDept entity) {
        return deptService.update(entity);
    }

    /**
     * 保存拖拽数据(父节点和路径)
     */
    @ResponseBody
    @PostMapping("/dnd")
    @Authorize(code = "SystemDepartment.Drag")
    public RestMessage dnd(@RequestBody List<TreeNodeIndex> nodeIndexs) {
        return deptService.batchUpdate(TreeHelper.toPrimaryKeyValues(nodeIndexs));
    }

    /**
     * 修改组织机构启用状态
     */
    @ResponseBody
    @PostMapping("/status")
    @Authorize(code = "SystemDepartment.Status")
    public RestMessage status(String id, Integer status) {
        return deptService.updateStatus(id, ConvertHelper.toBool(status));
    }

    /**
     * 删除组织机构
     */
    @ResponseBody
    @PostMapping("/delete")
    @Authorize(code = "SystemDepartment.Delete")
    public RestMessage delete(String ids) {
        return deptService.delete(ids);
    }

    /**
     * 导出组织机构
     */
    @GetMapping("/export")
    @Authorize(code = "SystemDepartment.Export")
    public void export(DeptFilter filter) {
        ExcelHelper.exportWeb(deptService.selectList(filter), SysDept.class, "系统组织机构");
    }

    //endregion
}